package cn.ecut.Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.ecut.Bean.User;
import cn.ecut.DBConnection.OpenConnection;

public class UserDao{
    public User userLogin(String username, String passwords) {
        User user = null;
        PreparedStatement pst = null;
        OpenConnection db = new OpenConnection();
        Connection conn = db.getConnection();
        String sql = "select name,password from users where name= ? and password= ?";
        try{
            pst = conn.prepareStatement(sql);
            pst.setString(1,username);
            pst.setString(2,passwords);
            ResultSet rs = pst.executeQuery();
            if (rs.next()){
                user = new User();
                user.setUsername(rs.getString("name"));
                user.setPassword(rs.getString("password"));
            }
            rs.close();
            pst.close();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return user;
    }
    public boolean register(User user){
        OpenConnection db = new OpenConnection();
        Connection conn = db.getConnection();
        String sql = "insert into users(name, password,phone,email) values(?,?,?,?)";
        int i = 0;
        try{
            conn.setAutoCommit(false);//设置为不自动提交
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setString(1, user.getUsername());
            pst.setString(2, user.getPassword());
            pst.setString(3, user.getPhone());
            pst.setString(4, user.getEmail());
            i = pst.executeUpdate();
            conn.commit();//提交以上操作
            pst.close();
        } catch (SQLException e){
            e.printStackTrace();
        }
        return i > 0;
    }

}
